package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.common.exceptionhandler.BusiException;
import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        Converter converter = source -> {
            T[] constants = targetType.getEnumConstants();
            if (constants != null && constants.length > 0) {
                for (T constant : constants) {
//                    if (source.equals(String.valueOf(constant.getCode()))) {
//                        return constant;
//                    }
                    if (source.equals(constant.getCode().toString())) {
                        return constant;
                    }
                }
            }
            throw new BusiException(208,"类型转换异常");
//            return null;
        };

        return converter;



//        return new Converter<String, T>() {
//            @Override
//            public T convert(String source) {
//                T[] constants = targetType.getEnumConstants();
//                for (T constant : constants) {
//                    if (constant.getCode().equals(Integer.valueOf(source))) {
//                        return constant;
//                    }
//                }
//                return null;
//            }
//        };
    }
}
